package com.vast.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vast.admin.entity.Contract;
import com.vast.admin.entity.Placeholder;
import com.vast.admin.utils.PlaceholderResolver;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vast.admin.mapper.ContractPlaceholderMapper;
import com.vast.admin.entity.ContractPlaceholder;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ContractPlaceholderService extends ServiceImpl<ContractPlaceholderMapper, ContractPlaceholder> {

    @Autowired
    private PlaceholderService placeholderService;

    /**
     * 批量保存合同占位符值
     * @param contractId
     * @param contractDetailId
     * @param templeteRecordId
     * @param contractParam
     */
    @Transactional
    public void saveContractPlaceholder(Long contractId, Long contractDetailId, Long templeteRecordId, Map<String, String> contractParam) {
        List<Placeholder> placeholders = placeholderService.getPlaceholder(templeteRecordId);
        List<ContractPlaceholder> contractPlaceholders = new ArrayList<>(placeholders.size());
        for (Placeholder placeholder : placeholders) {
            ContractPlaceholder contractPlaceholder = new ContractPlaceholder();
            BeanUtils.copyProperties(placeholder, contractPlaceholder);
            contractPlaceholder.setContractId(contractId);
            contractPlaceholder.setContractDetailId(contractDetailId);
            contractPlaceholder.setTemplateId(placeholder.getTempleteId());
            contractPlaceholder.setTemplateRecordId(placeholder.getTempleteRecordId());
            contractPlaceholder.setPlaceholderId(placeholder.getId());
            contractPlaceholder.setPlaceholderValue(contractParam.get(placeholder.getPlaceholderKey()));
            contractPlaceholder.setCreateTime(new Date());
            contractPlaceholder.setUpdateTime(new Date());
            contractPlaceholders.add(contractPlaceholder);
        }
        super.saveBatch(contractPlaceholders);
    }

    /**
     * templeteRecordId获取
     * @param templeteRecordId
     * @return
     */
    public List<ContractPlaceholder> getByTemplateRecordId(Long templeteRecordId) {
        QueryWrapper<ContractPlaceholder> contractPlaceholderQueryWrapper = new QueryWrapper<>();
        contractPlaceholderQueryWrapper.eq(ContractPlaceholder.COL_TEMPLATE_RECORD_ID, templeteRecordId)
                .ne(ContractPlaceholder.COL_PLACEHOLDER_TAG, 4)
                .ne(ContractPlaceholder.COL_PLACEHOLDER_NAME, PlaceholderResolver.REPAYMENT_PLAN_FIELD);
        return super.list(contractPlaceholderQueryWrapper);
    }


}
